egen cluster1 = group(agency) if sample==1

mat TT = J(5,9,.)
mat colnames TT = business_w5 comply complete open_request extension business_days_within_15 business_days_within_25 business_days_15 business_days_25

mat rownames TT = "MDE" "Control_mean" "Control_SD" "ICC" "Baseline_correlation"

qui xtreg business_w5 if sample==1 & time==0, i(cluster1) re
loc m  =round(e(g_avg)) // g_avg --> Average group size
loc k  =round(e(N_g)/2) // N_g --> Number of clusters 
loc icc=e(rho) 

loc A = 1+(((`m'/2)-1)*`icc')
loc r = ((`m'/2)*`icc')/`A'

mat TT[4,1] = round(`icc',.001)
mat TT[5,1] = round(`r',.001)

sum business_w5 if sample==1 & treatment==0 & time==0
loc con_m = r(mean)
loc con_sd = r(sd)

mat TT[2,1] = round(`con_m',.001)
mat TT[3,1] = round(`con_sd',.001)

** Parameters to use
dis in red "`k' , `m', `icc', `r'" 

** Code by Hemming and Masch considering baseline correlation for a continuous variable 
clustersampsi, detectabledifference mu1(`con_m') sd1(`con_sd') rho(`icc') alpha(0.05) beta(0.8) m(`m') k(`k') base_correl(`r')
loc rdd = r(DD)

mat TT[1,1] = round(`rdd', .001)

local i 1
foreach v of global all_binary {
	dis in blue `v' 
	local ++i
	xtreg `v' if sample==1  & time==0, i(cluster1) re
	loc m  =round(e(g_avg))
	loc k  =round(e(N_g)/2)
	loc icc=e(rho)

	loc A = 1+(((`m'/2)-1)*`icc')
	loc r = ((`m'/2)*`icc')/`A'

	mat TT[4,`i'] = round(`icc',.001)
	mat TT[5,`i'] = round(`r',.001)

	su `v' if sample==1 & treatment==0 & time==0
	loc con_m = string(r(mean), "%9.3f")
	loc con_sd = string(r(sd), "%9.3f")

	mat TT[2,`i'] = round(`con_m',.001)
	mat TT[3,`i'] = round(`con_sd',.001)


	** Parameters to use
	dis in red "`k' , `m', `icc', `r'" 

	** Code by Hemming and Masch considering baseline correlation for a continuous variable 
	clustersampsi, binomial detectabledifference p1(`con_m')  rho(`icc') alpha(0.05) beta(0.8) m(`m') k(`k') base_correl(`r')
	
	loc rdd = r(DD_pos)

	mat TT[1,`i'] = round(`rdd', .001)
}

outtable using "$Tables/Table_C1", replace mat(TT) nobox center caption(Power Calculation) clabel(tab:Power) f(%9.3f %9.3f %9.3f %9.3f %9.3f %9.3f %9.3f %9.3f)
